package com.alan.shiro.api.controller;

import com.alan.shiro.api.bean.ResultMap;
import com.alan.shiro.api.bean.Role;
import com.alan.shiro.api.bean.User;
import com.alan.shiro.api.service.UserService;
import com.alan.shiro.api.token.StatelessToken;
import com.alan.shiro.api.token.manager.TokenManager;
import com.alan.shiro.api.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/11 19:18
 * @Description: LoginController
 */
@RestController
@Slf4j
public class LoginController {

    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public ResultMap getMessage() {
        User user = UserUtils.getCurrntUser();
        System.out.println("user:"+ JSON.toJSONString(user));
        return new ResultMap().success().message("您拥有用户权限，可以获得该接口的信息！");
    }

    @Autowired
    private UserService userService;

    @Autowired
    private TokenManager tokenManager;


    @RequestMapping(value = "login",method = RequestMethod.POST)
    public ResultMap login(String username, String password) {
        log.info("username:"+username);
        User usr = userService.select(username);
        if (usr == null) {
            return new ResultMap().fail().message("valid user");
        }
        if(!password.equals(usr.getPassword())){
            return new ResultMap().fail().message("valid user password");
        }
        //成功穿件token返回给客户端保存
        StatelessToken createToken = null;
        ResultMap resultMap = new ResultMap();
        try {
            createToken = tokenManager.createToken(usr.getId().toString());
            resultMap.success().message(createToken);
        } catch (Exception e) {
            log.error("token 生成异常：{}",e);
            resultMap.fail().message("\"token 生成异常");
        }
        return resultMap;
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public ResultMap logout(HttpServletRequest request) {
        String authorization = request.getHeader("authorization");
        StatelessToken token = tokenManager.getToken(authorization);
        if(token!= null){
            tokenManager.deleteToken(token.getUserId().toString());
        }
        SecurityUtils.getSubject().logout();
        log.info("用户登出");
        return new ResultMap().success().message("logout success");
    }

}
